<template>
  <div class="app-container">
    <el-form :model="queryParams" v-show="showSearch" ref="queryForm" :inline="true">
      <el-form-item label="流程实例ID" prop="processInstanceId">
        <el-input
          v-model="queryParams.processInstanceId"
          placeholder="流程实例ID精确查询"
          clearable
          size="default"
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="流程编码" prop="wfCodeLike">
        <el-input
          v-model="queryParams.wfCodeLike"
          placeholder="流程编码模糊查询"
          clearable
          size="default"
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="业务KEY" prop="businessKeyLike">
        <el-input
          v-model="queryParams.businessKeyLike"
          placeholder="业务Key模糊查询"
          clearable
          size="default"
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="流程主题" prop="businessSubjectLike">
        <el-input
          v-model="queryParams.businessSubjectLike"
          placeholder="主题模块查询"
          clearable
          size="default"
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="待办创建时间">
        <el-date-picker
          v-model="dateRange"
          size="default"
          style="width: 240px"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item label="被代理人" prop="proxyTargetId">
        <el-select v-model="queryParams.proxyTargetId" placeholder="选择被代理人" style="width: 240px">
          <el-option
            v-for="item in proxyTargetOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <search-button @click="handleQuery" />
        <reset-button @click="resetQuery" />
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <right-toolbar @query-table="handleQuery" v-model:showSearch="showSearch" />
    </el-row>
    <el-table v-loading="loading" :data="todoList">
      <el-table-column label="被代理人" prop="originalCandidate" width="200" align="center">
        <template #default="scope">
          <span>{{
            scope.row.originalCandidate &&
              scope.row.originalCandidate.userName + '(' + scope.row.originalCandidate.loginName + ')'
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="流程实例ID" prop="processInstanceId" width="240" align="center" />
      <el-table-column
        label="业务KEY"
        prop="businessKey"
        width="150"
        align="center"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="流程主题"
        prop="businessSubject"
        min-width="250"
        align="center"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="审批节点" prop="taskName" min-width="160" align="center" />
      <el-table-column
        label="流程名称"
        prop="deploymentName"
        min-width="240"
        align="center"
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <span>{{ scope.row.deploymentName + '(' + scope.row.processDefinitionId + ')' }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="流程发起人"
        prop="userName"
        width="220"
        align="center"
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <span>{{
            scope.row.starter &&
              scope.row.starter.userName + '(' + scope.row.starter.loginName + ')'
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发起时间" prop="processCreateTime" width="160" align="center">
        <template #default="scope">
          <span>{{ parseTime(scope.row.processCreateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="提交时间" prop="taskCreateTime" width="160" align="center">
        <template #default="scope">
          <span>{{ parseTime(scope.row.taskCreateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="240"
        fixed="right"
      >
        <template #default="scope">
          <text-edit-button text="办理" @click="showApplyModal(scope.row)" />
          <text-detail-button text="审批记录" @click="showAppHistoryModal(scope.row)" />
          <text-detail-button text="流转过程" @click="showFlowImgModal(scope.row)" />
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 办理 level: approveUrl  approveFrameUrl-->
    <drag-dialog
      :title="title"
      :close-on-click-modal="false"
      v-model="applyCommonOpen"
      append-to-body
      width="90%"
      @close="applyCloseHandler"
    >
      <wf-approve v-if="applyCommonOpen" :approveObject="applyObject" @close="applyCloseHandler" />
    </drag-dialog>

    <!-- 查询审批记录 -->
    <drag-dialog
      :title="title"
      :close-on-click-modal="false"
      v-model="showHistoryOpen"
      width="90%"
      append-to-body
    >
      <wf-approve-history
        :processInstanceId="processInstanceId"
        :wfStatusOptions="wfStatusOptions"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">关闭</el-button>
        </div>
      </template>
    </drag-dialog>

    <!-- 查看审批过程 -->
    <drag-dialog
      :title="title"
      :close-on-click-modal="false"
      v-model="showFlowOpen"
      width="90%"
      append-to-body
    >
      <bpmn-viewer v-if="isFlowable && showFlowOpen" :taskId="taskId" :wfCode="wfCode" :processInstanceId="processInstanceId" :deploymentId="deploymentId" />
      <wf-run-image
        v-else
        :processInstanceId="processInstanceId"
        :formModelVersionId="formModelVersionId"
        :showCurrentApproverList="showCurrentApproverList"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">关闭</el-button>
        </div>
      </template>
    </drag-dialog>
  </div>
</template>
<script>
import {
  listWfProxyTodo,
  getApproveHistory,
  showFlowRunImgByInstantId,
  getProcessRunTaskAndApprover,
  getWfButton
} from '@wf/api/wf/task/todo'
import { assign } from 'lodash-es'
import { debounceWrapper } from '@/utils/zmids'
import WfApprove from '@/components/Zmids/Workflow/WfApprove.vue'
import WfRunImage from '@/components/Zmids/Workflow/WfRunImage.vue'
import WfApproveHistory from '@/components/Zmids/Workflow/WfApproveHistory.vue'
import BpmnViewer from '@wf/components/bpmnjs/bpmnViewer'
import {searchProxyTargetUser} from "@/platform/wf/api/wf/task/proxySetting.js";

export default {
  name: 'MyTodoProxy',
  components: { BpmnViewer, WfApprove, WfApproveHistory, WfRunImage },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选择的流程实例ID
      processInstanceId: '',
      deploymentId: '',
      taskId: '',
      // 是否显示当前审批人列表
      showCurrentApproverList: false,
      // 总条数
      total: 0,
      // 流程表格数据
      todoList: [],
      showHistoryList: [],
      // 显示搜索条件
      showSearch: true,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        processInstanceId: undefined,
        wfCodeLike: undefined,
        businessKeyLike: undefined,
        businessSubjectLike: undefined
      },
      //dialog弹出框
      applyCommonOpen: false,
      showHistoryOpen: false,
      showFlowOpen: false,
      //dialog弹出框标题
      title: '',
      //流程状态
      wfStatusOptions: [],
      //流程办理row
      applyObject: {},
      //传给审批页面内嵌URL的参数
      param: {},
      buttons: {}, //审批页面的按钮
      formModelVersionId: '', //低代码表单版本ID
      wfCode: '',
      proxyTargetOptions: [], // 被代理人列表
      // 查询被代理人列表参数
      queryProxyTargetParams: {
        pageNum: null,
        pageSize: null,
      },
    };
  },
  computed: {
    isFlowable(){
      return import.meta.env.VITE_FLOW_TYPE == 'flowable'
    }
  },
  created() {
    //初始化
    this.getList()
    this.getProxyTargetList()
    this.getDicts('wf_approve_status').then((response) => {
      this.wfStatusOptions = response.data
    })
  },
  methods: {
    //刷新按钮刷新
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
      this.getProxyTargetList()
    },
    // 重置按钮操作
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    //查询
    getList: debounceWrapper(function () {
      this.loading = true
      listWfProxyTodo(
        this.addDateRange(
          this.queryParams,
          ['taskCreateTimeStart', 'taskCreateTimeEnd'],
          this.dateRange
        )
      ).then((response) => {
        this.todoList = response.data.list
        this.total = response.data.total
        this.loading = false
      })
    }),
    // 查询被代理用户列表
    getProxyTargetList(){
        this.loading = true;
        searchProxyTargetUser(this.queryProxyTargetParams).then(
            response => {
              this.proxyTargetOptions = []
              response.data.list.map(item => {
                this.proxyTargetOptions.push(
                    {
                      label: item.proxyTargetName,
                      value: item.proxyTargetId
                    }
                )
              })
              this.loading = false;
            }
        )
    },
    // 刷新
    handRefresh() {
      this.getList()
    },
    //重置
    reset(event) {
      this.title = ''
      // 选择的流程实例ID
      this.processInstanceId = ''
      this.deploymentId = ''
      this.taskId = ''
      this.formModelVersionId = ''
      // 是否显示当前审批人列表
      this.showCurrentApproverList = false
      this.applyObject = {}
      this.showHistoryList = []

      // 不是关闭按钮则刷新
      if (event !== undefined && 'closeHandler' !== event) {
        this.handRefresh()
      }
    },
    // 办理
    showApplyModal: debounceWrapper(async function (row) {
      //TODO 流程ID 流程标题 流程组件地址
      this.title = row.businessSubject
      this.applyObject = row
      this.applyObject.originalCandidate = row.originalCandidate
      this.applyObject.approveUrl = row.approveUrl
      this.applyObject.approveFrameUrl = row.approveFrameUrl
      this.param = row.params
      assign(this.param, this.param, {
        processInstanceId: row.processInstanceId
      })
      this.applyCommonOpen = true
      // getWfButton(row.taskId).then((response) => {
      //   this.applyCommonOpen = true;
      //   this.buttons = response.data;
      // });
    }),
    applyCloseHandler(event, params) {
      console.log('关闭Dialog页面，event=', event, 'params', params)
      this.applyCommonOpen = false
      this.reset(event)
      // // 不是关闭按钮则刷新
      // if (event !== undefined && "closeHandler" !== event) {
      //   this.handRefresh();
      // }
    },

    // 查询审批记录
    showAppHistoryModal: debounceWrapper(function (row) {
      this.title = '审批记录'
      this.showHistoryOpen = true
      this.processInstanceId = row.processInstanceId
    }),
    // 查看流转过程
    showFlowImgModal: debounceWrapper(function (row) {
      this.title = '查看流转过程'
      this.showFlowOpen = true
      this.deploymentId = row.deploymentId
      this.processInstanceId = row.processInstanceId
      this.taskId = row.taskId
      this.formModelVersionId = row.params ? row.params.formModelVersionId : undefined
      this.showCurrentApproverList = true
    }),
    // 统一取消按钮
    cancel() {
      this.showHistoryOpen = false
      this.showFlowOpen = false
      this.reset()
    }
  }
}
</script>
<style lang="scss" scoped></style>
